/**
 * 
 */
package Verifier;

import java.io.UnsupportedEncodingException;

/**
 * Class to convert string to byte array and backwards
 * @author Moshe Baavur
 *
 */
public class GeneralUtils {

	/**
	 * Converts the string into an array of bytes.
	 * 
	 * @param text the string to convert.
	 * @param encoding the encoding type of the string.
	 * @return the array of bytes representing the string. If the conversion is not successful, an empty array is returned.
	 */
	public static byte[] convertStringToBytes(String text, String encoding) {
		// try to convert the text into bytes
		try {
			return (text.getBytes("ASCII"));
		} catch (UnsupportedEncodingException e) {}
		// can't convert  - return clean array
		return (new byte[0]);
	}
	
	/**
	 * Converts the string into an array of bytes, while treating the string as an ASCII string.
	 * This is exactly as calling convertStringToBytes(text, "ASCII").
	 * 
	 * @param text the string to convert.
	 * @return the array of bytes representing the string. If the conversion is not successful, an empty array is returned.
	 */
	public static byte[] convertStringToBytes(String text) {
		return (convertStringToBytes(text, "ASCII"));
	}
	
	/**
	 * Converts the bytes array into a string.
	 * 
	 * @param text the array of bytes to convert.
	 * @param encoding the encoding type of the bytes array.
	 * @return the string that represents the array of bytes. If the conversion is not successful, an empty string is returned.
	 */
	public static String convertBytesToString(byte[] text, String encoding) {
		// try to convert the text bytes into a string
		try {
			return (new String(text, "ASCII"));
		} catch (UnsupportedEncodingException e) {}
		// can't convert - return clean string
		return ("");
	}
	
	/**
	 * Converts the bytes array into a string, while treating the bytes representing an ASCII string.
	 * This is exactly as calling convertBytesToString(text, "ASCII").
	 * 
	 * @param text the array of bytes to convert.
	 * @return the string that represents the array of bytes. If the conversion is not successful, an empty string is returned.
	 */
	public static String convertBytesToString(byte[] text) {
		return (convertBytesToString(text, "ASCII"));
	}
}
